﻿/*
 * Created by SharpDevelop.
 * User: lebeda
 * Date: 7.5.2014
 * Time: 6:56
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace simpleExplorer
{
	/// <summary>
	/// Description of ExecLog.
	/// </summary>
	public class ExecLog
	{
		
		private static string execLogNameXml = Tools.configDirName() + Tools.FS_SEPARATOR + "execLog.xml";
		
		private ExecLog()
		{
		}
		
		public static Dictionary<string, int> load()
		{
			return Deserialize(execLogNameXml);
		}
		
		public static void writeOnExecute(string key)
		{
			// read
			var execlog = load();
			
			// increment
			int count = 0;
			if (execlog.ContainsKey(key)) {
				count = execlog[key];
			}
			execlog[key] = ++count;
			
			// write
			Serialize(execLogNameXml, execlog);
		}

		static void Serialize(string path, Dictionary<string, int> data)
		{
			List<ExecLogItem> execlogList = new List<ExecLogItem>(data.Count);
			foreach (var pair in data) {
				if (pair.Value > 0) {
					execlogList.Add(new ExecLogItem(pair.Key, pair.Value));
				}
			}
			
			execlogList = execlogList.OrderByDescending(o=>o.count).ToList();
				
			
			XmlSerializer serializer = new XmlSerializer(typeof(List<ExecLogItem>));
			StreamWriter writer = new StreamWriter(path);
		    serializer.Serialize(writer, execlogList);
		    writer.Close();
			
		}
		
		static Dictionary<string,int> Deserialize(string path)
		{
			if (File.Exists(path)) {
				try {
					
					XmlSerializer deserializer = new XmlSerializer(typeof(List<ExecLogItem>));
            		TextReader textReader = new StreamReader(path);
            		List<ExecLogItem> execlogList;
            		execlogList = (List<ExecLogItem>)deserializer.Deserialize(textReader);
            		textReader.Close();
					
            		var data = new Dictionary<string, int>();
            		foreach (ExecLogItem execLogItem in execlogList) {
            			data[execLogItem.caption] = execLogItem.count;
            		}    
			
					return data;            		
					
				} catch(Exception e) {
					Console.WriteLine("IOException: {0}", e.Message);
					File.Delete(path);
					return new Dictionary<string, int>();					
				}
			} else {
				return new Dictionary<string, int>();
			}
		}
	}
}
